<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

class PermissionRepository
{

    /**
     * 查看菜单详情(目前暂时只支持二级菜单)
     *
     * @param $menu_id
     * @param  bool|false  $is_top
     * @return mixed
     */
    public function menuDetailById($menu_id, $is_top = false)
    {
        $menu = app('model_menu')->where('menu_id', $menu_id);
        if ($is_top) {
            $menu->where('parent_id', 0);
        }
        $menu = $menu->first();

        return $menu;
    }


    /**
     * 新增菜单
     *
     * @param  array  $param
     * @return bool
     * @throws BasicException
     */
    public function menuAdd($param = [])
    {
        $res = app('model_menu')->create($param);
        if ($res) {
            return true;
        }
        throw new BasicException(20051);
    }


    /**
     * 菜单列表
     *
     * @param $param
     * @param  int  $page
     * @param  int  $perPage
     * @return \Laravel\Lumen\Application|mixed
     */
    public function menuList($param, $page = 1, $perPage = 10)
    {
        $list = app('model_menu');
        if (!empty($param['level'])) {
            $list = $list->where('level', $param['level']);
        }
        if (!empty($param['status'])) {
            $list = $list->where('status', $param['status']);
        }
        if (!empty($param['search'])) {
            $list = $list->where('menu_name', 'like', "%{$param['search']}%");
        }
        $list = $list->orderBy('add_time', 'desc')->paginate($perPage, ['*'], '', $page);

        foreach ($list as &$val) {
            $val->add_time = date('Y-m-d H:i:s', $val->add_time);
        }

        return $list;
    }


    /**
     * 编辑菜单
     *
     * @param $menu_id
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function menuUpdate($menu_id, $param)
    {
        //检测menu是否存在
        $menu = $this->menuDetailById($menu_id);
        if (empty($menu)) {
            throw new BasicException(20052);
        }

        if (!empty($param['menu_name'])) {
            $menu->menu_name = $param['menu_name'];
        }
        if (!empty($param['menu_key'])) {
            $menu->menu_key = $param['menu_key'];
        }
        if (!empty($param['status'])) {
            $menu->status = $param['status'];
        }
        if (!empty($param['icon'])) {
            $menu->icon = $param['icon'];
        }
        if (!empty($param['level'])) {
            $menu->level = $param['level'];
        }
        if (!empty($param['sort'])) {
            $menu->sort = $param['sort'];
        }
        if (isset($param['parent_id'])) {
            $menu->parent_id = $param['parent_id'];
        }

        $res = $menu->save();
        if ($res) {
            return true;
        }
        throw new BasicException(20053);
    }


    /**
     * 添加权限
     *
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function permissionAdd($param)
    {
        $res = app('model_permission')->create($param);
        if ($res) {
            return true;
        }
        throw new BasicException(90002);
    }


    /**
     * 菜单列表
     *
     * @param $menu_id
     * @param  int  $page
     * @param  int  $perPage
     * @return \Laravel\Lumen\Application|mixed
     */
    public function permissionList($menu_id, $page = 1, $perPage = 10, $pmsName = '')
    {
        $list = app('model_permission');
        if ($menu_id) {
            $list = $list->where('menu_id', $menu_id);
        }

        $list = $list->where(function ($query) use ($pmsName) {
            if ($pmsName) {
                $query->where('permission_name', 'like', "%{$pmsName}%");
            }
        })->with('menu')->orderBy('add_time', 'desc')->paginate($perPage, ['*'], '', $page);

        //遍历列表
        foreach ($list as &$val) {
            $val->menu_name = isset($val->menu->menu_name) ? $val->menu->menu_name : '';
            $val->add_time = date('Y-m-d H:i:s', $val->add_time);
            unset($val->menu);
        }

        return $list;
    }


    /**
     * 编辑权限
     *
     * @param $permission_id
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function permissionUpdate($permission_id, $param)
    {
        $permission = $this->permissionDetail($permission_id);
        if (empty($permission)) {
            throw new BasicException(20055);
        }

        if (!empty($param['permission_name'])) {
            $permission->permission_name = $param['permission_name'];
        }
        if (!empty($param['permission_key'])) {
            $permission->permission_key = $param['permission_key'];
        }
        if (!empty($param['menu_id'])) {
            $permission->menu_id = $param['menu_id'];
        }
        if (!empty($param['method'])) {
            $permission->method = $param['method'];
        }

        $res = $permission->save();
        if ($res) {
            return true;
        }
        throw new BasicException(90003);
    }


    /**
     * 查询permission详情
     *
     * @param $permission_id
     * @return mixed
     */
    public function permissionDetail($permission_id)
    {
        $permission = app('model_permission')->where('permission_id', $permission_id)->first();

        return $permission;
    }


    /**
     * 根据权限ID数组返回数据集数量
     *
     * @param $ids
     * @return mixed
     */
    public function getPermissionCountByIds($ids)
    {
        $count = app('model_permission')->whereIn('permission_id', $ids)->count();

        return $count;
    }

    /**
     * 根据菜单ID数组返回数据集数量
     *
     * @param $ids
     * @return mixed
     */
    public function getMenuCountByIds($ids)
    {
        $count = app('model_menu')->whereIn('menu_id', $ids)->count();

        return $count;
    }

    /**
     * 添加角色
     *
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function roleAdd($param)
    {
        $res = app('model_role')->create($param);
        if ($res) {
            return $res;
        }
        throw new BasicException(90004);
    }


    /**
     * 角色列表
     *
     * @param $param
     * @param  int  $page
     * @param  int  $perPage
     * @return \Laravel\Lumen\Application|mixed
     */
    public function roleList($param, $page = 1, $perPage = 10)
    {
        $list = app('model_role')->where('is_delete', 0);
        if (!empty($param['sc_id'])) {
            $list = $list->where('sc_id', $param['sc_id']);
        }
        if (!empty($param['status'])) {
            $list = $list->where('status', $param['status']);
        }
        if (!empty($param['search'])) {
            $list = $list->where('role_name', 'like', "%{$param['search']}%");
        }
        $list = $list->select('role_id', 'role_name', 'add_time', 'status', 'role_memo')->with("admin:admin_id,role_id,admin_name")->orderBy('add_time', 'desc')->paginate($perPage, ['*'], '', $page);

        foreach ($list as &$val) {
            $val->add_time = date('Y-m-d H:i:s', $val->add_time);
        }

        return $list;
    }

    /**
     *  获取所有角色
     *
     * @return mixed
     */
    public function getRole()
    {
        return app('model_role')->where('status', 1)->select('role_id', 'role_name')->get();
    }

    /**
     *  角色编辑
     *
     * @param $param
     * @return mixed
     */
    public function RoleEdit($param)
    {
        //        $modle_role = app('model_role')->where('role_id',$param['role_id'])->first();
        //
        //        if (isset($param['menu_arr'])) {
        //
        //            $menu_arr = explode(',',$modle_role->menu_arr);
        //            $menu_arr2 = explode(',',$param['menu_arr']);
        //
        //            if (!array_diff($menu_arr2,$menu_arr)) {
        //                unset($param['menu_arr']);
        //            }
        //
        //        }
        //        if (isset($param['permission_arr'])) {
        //            $permission_arr = explode(',',$modle_role->permission_arr);
        //            $permission_arr2 = explode(',',$param['permission_arr']);
        //            if (!array_diff($permission_arr2, $permission_arr)) {
        //                unset($param['permission_arr']);
        //            }
        //        }

        $role = app('model_role')->where('role_id', $param['role_id'])->update($param);

        if ($role !== false) {
            return true;
        }
        throw new BasicException(20062);
    }


    /**
     * 根据role_id获取role详情
     *
     * @param $role_id
     * @return mixed
     */
    public function roleDetail($role_id)
    {
        $role = app('model_role')->where('role_id', $role_id)->first();
        //$role['menu_arr'] = $this->getAllMenusByIds(explode(',',$role->menu_arr));
        //$role['menu_arr'] = $this->getNavMenus(explode(',',$role->menu_arr));
        //$role['permission_arr'] = $this->getAdminPermission(explode(',',$role->permission_arr));
        return $role;
    }


    /**
     * @param $type 菜单的类型1公会2厅
     * @param $pid  菜单的父级ID,默认会查出显示中的一级菜单
     * @return \Laravel\Lumen\Application|mixed
     */
    public function getMenuList($type, $pid)
    {
        $list = app('model_menu');
        if (!empty($type)) {
            $list = $list->where('type', $type);
        }
        $list = $list->where(['parent_id' => $pid, 'status' => 1])->select('menu_id', 'menu_name', 'level')->get();

        return $list;
    }


    /**
     * 获取所有菜单的数据(树形数据)
     *
     * @return mixed
     */
    public function getAllMenu()
    {
        $list = app('model_menu')->where('parent_id', 0)->with('hasManyMenus')->orderBy('sort', 'desc')->get();

        return $list;
    }


    /**
     * 获取所有菜单,权限联系数据
     *
     * @return mixed
     */
    public function getAllPermission()
    {
        $c_list = app('model_menu')->where('parent_id', '>', 0)->with('hasManyPermission')->orderBy('sort', 'desc')->get();

        //查询顶级的菜单
        $top_list = app('model_menu')->where('parent_id', 0)->orderBy('sort', 'desc')->get();

        //最低效的写法,先实现,后期数据量大再改进
        foreach ($top_list as &$val) {
            $array = [];
            foreach ($c_list as &$nal) {
                if ($nal->parent_id == $val->menu_id) {
                    $array[] = $nal;
                }
            }
            $val->children = $array;
        }

        return $top_list;
    }

    /**
     * 获取所有菜单,权限联系数据
     *
     * @return mixed
     */
    public function getAllPermissionTree()
    {
        $c_list = app('model_permission')->all()->toArray();

        $tempMap = [];
        foreach ($c_list as $item) {
            if (!isset($tempMap[$item['parent_id']])) {
                $tempMap[$item['parent_id']] = [];
            }

            $tempMap[$item['parent_id']][] = [
                "menu_id"   => $item['permission_id'],
                "menu_name" => $item['permission_name'],
                "level"     => 3,
                "children"  => [],
            ];
        }

        $allMenuTree = $this->getAllMenu();

        //最低效的写法,先实现,后期数据量大再改进
        foreach ($allMenuTree as &$val) {
            if (isset($val['children'])) {
                foreach ($val['children'] as &$item) {
                    if (isset($tempMap[$item['menu_id']])) {
                        $item['children'] = $tempMap[$item['menu_id']];
                    }

                    $item['menu_id'] += 10000;
                }
            }
            $val['menu_id'] += 10000;
        }

        return $allMenuTree;
    }


    /**
     * 获取所有的权限ID数组
     *
     * @return array
     * @throws \Exception
     * @throws \Illuminate\Container\EntryNotFoundException
     */
    public function getPermissionIDArr()
    {
        $ids = [];
        $list = app('model_permission')->get(['permission_id'])->toArray();
        foreach ($list as $val) {
            if (!in_array($val['permission_id'], $ids)) {
                $ids[] = $val['permission_id'];
            }
        }

        return $ids;
    }


    /**
     * 根据id字串获得菜单数组
     *
     * @param  array  $ids
     * @return mixed
     */
    public function getAllMenusByIds($ids = [])
    {
        $list = app('model_menu')->whereIn('menu_id', $ids)->get();

        return $list;
    }


    /**
     * 登录获取导航菜单数据
     *
     * @param  array  $ids
     * @return array
     */
    public function getNavMenus($ids = [], $isAdmin = false)
    {
        $query = app('model_menu');
        if (!$isAdmin) {
            $query = $query->whereIn('menu_id', $ids);
        }

        $list = $query->orderBy('sort', 'desc')->get()->where('status', 1)->toArray();

        $data = [];
        $top_menu = [];
        foreach ($list as $val) {
            if ($val['parent_id'] == 0) {
                $children = [];
                $menus = [];
                foreach ($list as $nal) {
                    if ($nal['parent_id'] == $val['menu_id']) {
                        $menus['menu_id'] = $nal['menu_id'];
                        $menus['menu_name'] = $nal['menu_name'];
                        $menus['menu_key'] = $nal['menu_key'];
                        $menus['icon'] = $nal['icon'];
                        $menus['level'] = $nal['level'];
                        $children[] = $menus;
                    }
                }
                $top_menu['menu_id'] = $val['menu_id'];
                $top_menu['menu_name'] = $val['menu_name'];
                $top_menu['menu_key'] = $val['menu_key'];
                $top_menu['icon'] = $val['icon'];
                $top_menu['level'] = $val['level'];
                $top_menu['children'] = $children;
                $data[] = $top_menu;
            }
        }

        return $data;
    }


    /**
     * 根据权限编号字符串获取所有权限值
     *
     * @param $ids
     * @return mixed
     */
    public function getPermissionsByIds($ids)
    {
        $permissions = app('model_permission')->whereIn('permission_id', $ids)->get();

        return $permissions;
    }


    /**
     * 获取所有权限keys值的数组
     *
     * @param $ids
     * @return array
     */
    public function getAdminPermission($ids, $isAdmin = false)
    {
        $query = app('model_permission');
        if (!$isAdmin) {
            $query = $query->whereIn('permission_id', $ids);
        }

        $permissions = $query->get();
        $keys_arr = [];

        foreach ($permissions as &$val) {
            if ($val) {
                $keys_arr[] = $val->toArray();
            }
        }

        return $keys_arr;
    }


    /**
     * 根据type获得所有menuid的字串
     *
     * @param $type
     * @return string
     */
    public function getMenusStrByType($type)
    {
        $menus = app('model_menu')->where('type', $type)->select('menu_id')->get();
        $str = '';
        foreach ($menus as &$val) {
            $str .= $val->menu_id . ',';
        }
        //去掉最后一位
        $str = substr($str, 0, -1);

        return $str;
    }


    /**
     * 根据菜单字串返回所有权限id字串
     *
     * @param $menuStr
     * @return string
     */
    public function getPermissionStrByMenuId($menuStr)
    {
        $permissions = app('model_permission')->whereIn('menu_id', explode(',', $menuStr))->select('permission_id')->get();
        $str = '';
        foreach ($permissions as &$val) {
            $str .= $val->permission_id . ',';
        }
        //去掉最后一位
        $str = substr($str, 0, -1);

        return $str;
    }


    /**
     * 获取所有正常状态的角色编号名称数组
     *
     * @return array
     */
    public function getAllRoleList()
    {
        $list = app('model_role')->where('is_delete', 0)->select('role_id', 'role_name')->get();

        $data = [];
        foreach ($list as &$val) {
            $data[$val->role_id] = $val->role_name;
        }

        return $data;
    }

    /**
     * 判断是否能够删除角色
     *
     * @param  int  $id
     * @return bool
     */
    public function canDelnrole(int $id)
    {
        $role = app('model_role')->where('is_delete', 0)->where('role_id', $id)->first();
        //        var_dump($role);
        if (empty($role)) {
            throw  new BasicException(10001, '没有该角色');
        }
        //判断角色下是否有管理员在使用
        $roleAdmin = app('model_admin')->where('status', 1)->where('role_id', $id)->first();

        if ($roleAdmin) {
            throw  new BasicException(10001, '角色下还有管理员（' . $roleAdmin->admin_name . '）不能删除');
        }
        $role->is_delete = 1;
        $role->save();

        return true;
    }
}


?>